package cn.hsp.harmonyosdemos.slice;

import cn.hsp.harmonyosdemos.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.window.dialog.ToastDialog;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;

/**
 * 厦门大学计算机专业 | 前华为工程师
 * 专注《零基础学编程系列》https://cxyxy.blog.csdn.net/article/details/121134634
 * 包含：Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
 * 公众号：花生皮编程
 */
public class MainAbilitySlice extends AbilitySlice {
    private Preferences preferences;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        DatabaseHelper databaseHelper = new DatabaseHelper(getContext());
        String filename = "pdb";
        preferences = databaseHelper.getPreferences(filename);

        findComponentById(ResourceTable.Id_writeText).setClickedListener(component -> write());
        findComponentById(ResourceTable.Id_readText).setClickedListener(component -> read());
        findComponentById(ResourceTable.Id_modifyText).setClickedListener(component -> modify());
        findComponentById(ResourceTable.Id_delText).setClickedListener(component -> del());
    }

    private void write() {
        preferences.putString("name", "花生皮编程");
        preferences.flush();
    }

    private void read() {
        String name = preferences.getString("name", "数据不存在");
        new ToastDialog(getContext()).setText(name).show();
    }

    private void modify() {
        preferences.putString("name", "花生皮编程2");
        preferences.flush();
    }

    private void del() {
        preferences.delete("name");
    }
}
